package com.th.cash.th2.login

import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.LinearLayout
import com.th.resmodel.R
import com.th.resmodel.databinding.LayoutVerificationCodeBinding

class VerificationCodeView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {

    private val binding: LayoutVerificationCodeBinding
    private val editTexts = mutableListOf<EditText>()
    private var onCodeCompleteListener: ((String) -> Unit)? = null

    init {
        binding = LayoutVerificationCodeBinding.inflate(LayoutInflater.from(context), this, true)
        initViews()
        setupTextWatchers()
        setupKeyListeners()
    }

    private fun initViews() {
        editTexts.apply {
            add(binding.etCode1)
            add(binding.etCode2)
            add(binding.etCode3)
            add(binding.etCode4)
            add(binding.etCode5)
            add(binding.etCode6)
        }
        
        // 设置所有EditText的焦点监听
        editTexts.forEach { editText ->
            editText.setOnFocusChangeListener { _, hasFocus ->
                if (hasFocus) {
                    // 找到第一个空的EditText的位置
                    val firstEmptyIndex = editTexts.indexOfFirst { it.text.isEmpty() }
                    // 如果当前获得焦点的不是第一个空的EditText，则将焦点转移到第一个空的EditText
                    if (firstEmptyIndex != -1 && editTexts.indexOf(editText) != firstEmptyIndex) {
                        editTexts[firstEmptyIndex].requestFocus()
                    }
                }
            }
        }
    }

    private fun setupTextWatchers() {
        editTexts.forEachIndexed { index, editText ->
            editText.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
                override fun afterTextChanged(s: Editable?) {
                    if (s?.length == 1) {
                        // Update background for filled state
                        editText.setBackgroundResource(R.drawable.bg_code_input_filled)
                        
                        // Move to next EditText if not the last one
                        if (index < editTexts.size - 1) {
                            editTexts[index + 1].requestFocus()
                        } else {
                            // Last digit entered, check if all digits are filled
                            checkCodeCompletion()
                        }
                    } else if (s?.length == 0) {
                        // Update background for empty state
                        editText.setBackgroundResource(R.drawable.bg_code_input_empty)
                    }
                }
            })
        }
    }

    private fun setupKeyListeners() {
        editTexts.forEachIndexed { index, editText ->
            editText.setOnKeyListener { _, keyCode, event ->
                if (keyCode == KeyEvent.KEYCODE_DEL && event.action == KeyEvent.ACTION_DOWN) {
                    if (editText.text.isEmpty() && index > 0) {
                        // If current EditText is empty and not the first one, delete previous input
                        editTexts[index - 1].setText("")
                        editTexts[index - 1].requestFocus()
                        return@setOnKeyListener true
                    }
                }
                false
            }
        }
    }

    private fun checkCodeCompletion() {
        val code = StringBuilder()
        var isComplete = true
        
        editTexts.forEach { editText ->
            val text = editText.text.toString()
            if (text.isEmpty()) {
                isComplete = false
            }
            code.append(text)
        }
        
        if (isComplete) {
            onCodeCompleteListener?.invoke(code.toString())
        }
    }

    fun setOnCodeCompleteListener(listener: (String) -> Unit) {
        onCodeCompleteListener = listener
    }

    fun clearCode() {
        editTexts.forEach { editText ->
            editText.setText("")
            editText.setBackgroundResource(R.drawable.bg_code_input_empty)
        }
        editTexts[0].requestFocus()
    }

    fun getCode(): String {
        val code = StringBuilder()
        editTexts.forEach { editText ->
            code.append(editText.text.toString())
        }
        return code.toString()
    }

    fun showKeyBoard(){
        binding.etCode1.postDelayed({
            binding.etCode1.requestFocus()
            val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(binding.etCode1, InputMethodManager.SHOW_IMPLICIT)
        },200)
    }
} 